#!/usr/bin/env bash

# ----------------------------------------------------------------------
# Filename:   iptables-save.sh
# Version:    1.0
# Date:       2021/03/30
# Author:     laiyixin
# Email:      laiyixin@kylinos.com.cn
# History：
#             Version 1.0, 2021/03/30
# Function:   iptables-save - 备份系统防火墙策略
# Out:
#              0=> Success
#              1=> Fail
#              other=> TCONF
# ----------------------------------------------------------------------

## TODO: 使用ctrl+c退出
##
iptablesOnCtrlC() {
    echo "正在优雅的退出..."
    iptablesClean

    exit ${TFAIL}
}

## TODO: 用户界面
##
iptablesUSAGE() {
    cat >&1 <<EOF
--------- iptables-save - 备份系统防火墙策略 ---------
EOF
}

## TODO : 执行前的初始化
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
iptablesInit() {
    # 判断root用户
    if [ $(id -u) -ne 0 ]; then
        echo "Must use root ！"
        exit ${TCONF}
    fi

    # 信号捕获ctrl+c
    trap 'iptablesOnCtrlC' INT

    iptablesClean

}

## TODO : 执行进行时的方法
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
iptablesTest() {
    iptables-save >/etc/sysconfig/iptables.save
    iptablesRetParse "iptables-save to /etc/sysconfig/iptables.save"
}

## TODO : 执行收尾清除工作
##
iptablesClean() {
    echo "Clean ..."

}

## TODO: 解析函数返回值
## In  : $1 => log
iptablesRetParse() {
    local ret=$?
    local logstr=""

    if [ $# -eq 1 ]; then
        logstr="$1"
    fi

    if [ $ret -eq 0 ]; then
        echo "[pass] : ${logstr}"
    else
        echo "[fail] : ${logstr}"
        iptablesClean
        exit ${TFAIL}
    fi
}

## TODO : Main
## Out  :
##        0=> Success
##        1=> Fail
##        other=> TCONF
iptablesMain() {
    iptablesUSAGE

    iptablesInit

    iptablesTest

    iptablesClean

    return ${TPASS}
}

iptablesMain
exit $?
